package meatslope2.application;

import javax.microedition.khronos.opengles.GL10;

import meatslope2.gameengine.engine.Engine;
import meatslope2.gameengine.gameobjects.Player;
import meatslope2.gameengine.scene.Scene;
import android.view.KeyEvent;
import android.view.MotionEvent;

//TODO: make a lot of functions final
//TODO: probably add a systems registry: collision system, input system, time
//TODO: motion blur
//TODO: maybe set up pools of primitive types that you can use
public class Game extends Engine
{
	private final Scene scene;
	private final Player player;
	
	public Game(Scene scene)
	{
		super();
		
		if(scene == null)
			throw new IllegalArgumentException("scene argument cannot be null");
		
		Player player = scene.getPlayer();
		if(player == null)
			throw new IllegalArgumentException("scene argument doesn't have a player");
		
		this.scene = scene;
		this.player = player;
	}
	
	/**
	 * Main update cycle
	 * @throws InterruptedException
	 */
	@Override
	protected void update() throws InterruptedException 
	{
		super.update();
		
		this.scene.update();
	}
	
	/**
	 * Main draw cycle
	 * @throws InterruptedException
	 */
	@Override
	protected void draw(final GL10 pGL) throws InterruptedException
	{
		this.scene.draw(pGL);
	}

	@Override
	//TODO: there might be a better home for this, we'll look back further in development
	public boolean onKeyDownEvent(int keyCode) 
	{
		if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
			player.getVelocity().set(-1, 0);
		else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
			player.getVelocity().set(1, 0);

		return true;
	}

	@Override
	//TODO: there might be a better home for this, we'll look back further in development
	public boolean onKeyUpEvent(int keyCode) 
	{
		if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
			player.getVelocity().x = 0;
		else if(keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
			player.getVelocity().y = 0;
		
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{
		if(event.getAction() == MotionEvent.ACTION_MOVE)
		{
			player.getVelocity().set(0, 100);
		}
		else if(event.getAction() == MotionEvent.ACTION_CANCEL)
		{
			player.getVelocity().set(0, 0);
		}
		
		return true;
	}
}
